package com.igeek.boot.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.igeek.boot.config.LoginUser;
import com.igeek.boot.entity.Admin;
import com.igeek.boot.mapper.AdminMapper;
import com.igeek.boot.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-12-26
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AuthenticationManager authenticationManager;

    //根据用户名 查询 认证用户信息
    @Override
    public Admin findAdminByName(String username) {
        Admin admin = adminMapper.selectAdminByName(username);
        return admin;
    }

    //登录
    @Override
    public LoginUser login(Admin admin) {
        //将用户输入的用户名和密码  和 基于数据库查询到的认证用户信息 进行自动认证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(admin.getUsername(), admin.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if(ObjectUtil.isEmpty(authenticate)){
            //认证未通过
            throw new RuntimeException("查询到的用户名或者密码不正确");
        }
        //认证通过 获取认证后的用户信息
        LoginUser user = (LoginUser) authenticate.getPrincipal();
        return user;
    }
}
